import { defineStore } from 'pinia'
import router from '@/router'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    userId: localStorage.getItem('userId') || null,
    name: localStorage.getItem('name') || null,
    userType: localStorage.getItem('userType') || null,
    status: localStorage.getItem('status') || null
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    isAdmin: (state) => state.userType === 'admin',
    isEmployee: (state) => state.userType === 'employee',
    isCustomer: (state) => state.userType === 'customer',
    getUserId: (state) => state.userId
  },
  
  actions: {
    login({ token, user_id, name, user_type, status }) {
      this.token = token
      this.userId = user_id
      this.name = name
      this.userType = user_type
      this.status = status
      
      localStorage.setItem('token', token)
      localStorage.setItem('userId', user_id)
      localStorage.setItem('name', name)
      localStorage.setItem('userType', user_type)
      localStorage.setItem('status', status)
      // 根据用户类型跳转到不同页面
      if (user_type === 'admin') {
        console.log(user_type + '1')
        router.push('/admin/rooms')
      } else if (user_type === 'employee') {
        console.log(user_type + '2')
        router.push('/employee/orders')
      } else {
        console.log(user_type + '3')
        router.push('/')
      }
    },
    
    logout() {
      this.token = null
      this.userId = null
      this.name = null
      this.userType = null
      this.status = null
      
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('name')
      localStorage.removeItem('userType')
      localStorage.removeItem('status')
      
      router.push('/login')
    }
  }
})